package com.ruoyi.system.utils;

import com.ruoyi.system.domain.vo.PatchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * BSDiff工具类 - 专注于文件差异比较和补丁生成应用
 */
public class BsDiffUtil {
    private static final Logger logger = LoggerFactory.getLogger(BsDiffUtil.class);
    private static final int DEFAULT_TIMEOUT = 300; // 默认超时5分钟
    private static final int BUFFER_SIZE = 8192;
    private static String BSDIFF_CMD = "bsdiff";
    private static String BSPATCH_CMD = "bspatch";

    /**
     * 生成差异补丁文件并返回补丁文件大小（MB）
     */
    public static PatchResult generatePatchWithSize(File oldFile, File newFile, File patchFile) throws IOException {
        return generatePatchWithSize(oldFile, newFile, patchFile, DEFAULT_TIMEOUT);
    }

    public static PatchResult generatePatchWithSize(File oldFile, File newFile, File patchFile, long timeoutSeconds) throws IOException {
        validateInputFiles(oldFile, newFile, patchFile);
        ensureParentDirectoryExists(patchFile);

        Process process = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(
                    BSDIFF_CMD,
                    oldFile.getCanonicalPath(),
                    newFile.getCanonicalPath(),
                    patchFile.getCanonicalPath()
            ).redirectErrorStream(true);

            logger.info("Generating patch from {} to {}", oldFile.getName(), newFile.getName());
            process = pb.start();

            boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
            if (!finished) {
                throw new RuntimeException("Patch generation timeout after " + timeoutSeconds + " seconds");
            }

            boolean success = verifyProcessResult(process, patchFile);
            double sizeMB = success ? getFileSizeMB(patchFile) : 0.0;

            return new PatchResult(success, sizeMB, patchFile.length());
        } catch (Exception e) {
            throw new RuntimeException("Patch generation failed", e);
        } finally {
            if (process != null) process.destroy();
        }
    }

    /**
     * 生成差异补丁文件（保持原有方法兼容性）
     */
    public static boolean generatePatch(File oldFile, File newFile, File patchFile) throws IOException {
        return generatePatch(oldFile, newFile, patchFile, DEFAULT_TIMEOUT);
    }

    public static boolean generatePatch(File oldFile, File newFile, File patchFile, long timeoutSeconds) throws IOException {
        PatchResult result = generatePatchWithSize(oldFile, newFile, patchFile, timeoutSeconds);
        return result.isSuccess();
    }

    /**
     * 获取补丁文件大小（MB）- 独立方法
     */
    public static double getPatchFileSizeMB(File patchFile) {
        if (patchFile == null || !patchFile.exists()) {
            return 0.0;
        }
        return getFileSizeMB(patchFile);
    }

    /**
     * 批量生成差分包并返回包含文件大小的结果
     */
    public static Map<String, PatchResult> generatePatchBatchWithSize(File newFile, List<File> oldFiles, List<File> patchFiles, long timeoutSeconds) {
        Map<String, PatchResult> results = new HashMap<>();

        if (oldFiles.size() != patchFiles.size()) {
            throw new IllegalArgumentException("Old files and patch files lists must have same size");
        }

        for (int i = 0; i < oldFiles.size(); i++) {
            try {
                PatchResult result = generatePatchWithSize(oldFiles.get(i), newFile, patchFiles.get(i), timeoutSeconds);
                results.put(patchFiles.get(i).getName(), result);
            } catch (Exception e) {
                results.put(patchFiles.get(i).getName(), new PatchResult(false, 0.0, 0L));
                logger.error("Failed to generate patch for {}", oldFiles.get(i).getName(), e);
            }
        }

        return results;
    }

    /**
     * 应用补丁文件
     */
    public static boolean applyPatch(File oldFile, File patchFile, File outputFile) throws IOException {
        return applyPatch(oldFile, patchFile, outputFile, DEFAULT_TIMEOUT);
    }

    public static boolean applyPatch(File oldFile, File patchFile, File outputFile, long timeoutSeconds) throws IOException {
        validatePatchFiles(oldFile, patchFile, outputFile);
        ensureParentDirectoryExists(outputFile);

        Process process = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(
                    BSPATCH_CMD,
                    oldFile.getCanonicalPath(),
                    outputFile.getCanonicalPath(),
                    patchFile.getCanonicalPath()
            ).redirectErrorStream(true);

            logger.info("Applying patch to {}", oldFile.getName());
            process = pb.start();

            boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
            if (!finished) {
                throw new RuntimeException("Patch application timeout after " + timeoutSeconds + " seconds");
            }

            return verifyProcessResult(process, outputFile);
        } catch (Exception e) {
            throw new RuntimeException("Patch application failed", e);
        } finally {
            if (process != null) process.destroy();
        }
    }

    /**
     * 批量应用补丁文件
     */
    public static Map<String, Boolean> applyPatchBatch(File baseFile, List<File> patchFiles, List<File> outputFiles, long timeoutSeconds) {
        Map<String, Boolean> results = new HashMap<>();

        if (patchFiles.size() != outputFiles.size()) {
            throw new IllegalArgumentException("Patch files and output files lists must have same size");
        }

        for (int i = 0; i < patchFiles.size(); i++) {
            try {
                boolean success = applyPatch(baseFile, patchFiles.get(i), outputFiles.get(i), timeoutSeconds);
                results.put(outputFiles.get(i).getName(), success);
            } catch (Exception e) {
                results.put(outputFiles.get(i).getName(), false);
                logger.error("Failed to apply patch {}", patchFiles.get(i).getName(), e);
            }
        }

        return results;
    }

    // 验证工具可用性
    public static boolean isBsDiffAvailable() {
        try {
            // 尝试执行bsdiff命令（不带参数）
            Process process = new ProcessBuilder(BSDIFF_CMD).start();
            // 即使输出使用说明，退出码为0也表示工具可用
            boolean finished = process.waitFor(2, TimeUnit.SECONDS);
            return finished && process.exitValue() == 0;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isBsPatchAvailable() {
        try {
            Process process = new ProcessBuilder(BSPATCH_CMD, "--version").start();
            return process.waitFor(5, TimeUnit.SECONDS) && process.exitValue() == 0;
        } catch (Exception e) {
            logger.warn("bspatch command not available", e);
            return false;
        }
    }

    /**
     * 获取可用的 bsdiff 工具路径（如果需要自定义路径）
     */
    public static void setBsDiffCommandPath(String bsdiffPath, String bspatchPath) {
        BSDIFF_CMD = bsdiffPath;
        BSPATCH_CMD = bspatchPath;
    }

    /**
     * 获取当前配置的命令路径
     */
    public static String getBsDiffCommand() {
        return BSDIFF_CMD;
    }

    public static String getBsPatchCommand() {
        return BSPATCH_CMD;
    }

    // 私有辅助方法
    private static void validateInputFiles(File... files) {
        for (File file : files) {
            if (file == null) throw new IllegalArgumentException("File cannot be null");
        }
        if (!files[0].exists()) throw new IllegalArgumentException("Old file not exists: " + files[0]);
        if (!files[1].exists()) throw new IllegalArgumentException("New file not exists: " + files[1]);
    }

    private static void validatePatchFiles(File... files) {
        for (File file : files) {
            if (file == null) throw new IllegalArgumentException("File cannot be null");
        }
        if (!files[0].exists()) throw new IllegalArgumentException("Old file not exists: " + files[0]);
        if (!files[1].exists()) throw new IllegalArgumentException("Patch file not exists: " + files[1]);
    }

    private static void ensureParentDirectoryExists(File file) throws IOException {
        File parent = file.getParentFile();
        if (parent != null && !parent.exists() && !parent.mkdirs()) {
            throw new IOException("Failed to create directory: " + parent);
        }
    }

    private static boolean verifyProcessResult(Process process, File outputFile) throws IOException {
        String output = readProcessOutput(process.getInputStream());
        int exitCode = process.exitValue();

        if (exitCode != 0) {
            logger.error("Process failed with code {}: {}", exitCode, output);
            return false;
        }

        if (!outputFile.exists() || outputFile.length() == 0) {
            throw new IOException("Output file not generated properly");
        }

        logger.debug("Operation succeeded. Output size: {} bytes", outputFile.length());
        return true;
    }

    private static String readProcessOutput(InputStream input) throws IOException {
        try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            byte[] data = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = input.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            return buffer.toString(StandardCharsets.UTF_8.name());
        }
    }

    /**
     * 获取文件大小（MB）
     */
    private static double getFileSizeMB(File file) {
        if (file == null || !file.exists()) {
            return 0.0;
        }
        return file.length() / (1024.0 * 1024.0);
    }

    /**
     * 检查差分包是否有效
     */
    public static boolean isValidPatch(File patchFile) {
        if (patchFile == null || !patchFile.exists() || patchFile.length() == 0) {
            return false;
        }

        // 简单的有效性检查：文件大小应该大于0且小于原始文件
        return patchFile.length() > 0;
    }

    /**
     * 估算补丁应用后的文件大小（粗略估算）
     */
    public static long estimatePatchedFileSize(File oldFile, File patchFile) {
        if (!oldFile.exists() || !patchFile.exists()) {
            return 0;
        }

        // 简单的估算：旧文件大小 + 补丁文件大小 * 2（考虑到bsdiff的压缩特性）
        return oldFile.length() + patchFile.length() * 2;

    }
}